<template>
  <basic-container :btnFlag=true>
    <div class="card-border">
      <card-header :header-data="headerData"></card-header>
      <div class="form-group">
        <span class="form-label">规划成果名称:</span>
        <input type="text"
               name="key"
               v-model="keyword"
               id="searchInput"
               ref="searchInput"
               placeholder="请输入规划成果名称"
               style="width: 500px;"
               @keyup.enter="searchSubmit()">
        <div class="form-submit">
          <el-button type="warning"
                     size="small"
                     @click.stop="searchSubmit()">查询
          </el-button>
          <el-button type="info"
                     size="small"
                     @click.stop="searchReset()">重置
          </el-button>
        </div>
      </div>
      <transition name="fade" @before-leave="searchTransition()" @after-enter="searchTransition()">
        <div v-if="showAll">
          <div :class="{showAll:true,active:showAll}">
            <el-divider></el-divider>
            <avue-search ref="search" :option="option"
                         v-model="selectedOptions"
                         @change="handleChange">
              <template 
                v-slot:year='data'
              >
                <t-year ref='year' @change='y=>searchSubmit(y)'></t-year> 
              </template>             
            </avue-search>
          </div>
        </div>
      </transition>
      <div class="search-collapse">
        <div class="collapse-title"
             :class="{active:showAll}"
             @click="showAll = !showAll">
          <img v-if="!showAll"
               :src="`${publicPath}img/packdown.png`"
               class="collapse-title-img">
          <p v-if="!showAll"
             class="collapse-title-text">展开搜索条件22</p>
          <img v-if="showAll"
               :src="`${publicPath}img/packUp.png`"
               class="collapse-title-img">
          <p v-if="showAll"
             class="collapse-title-text">收起搜索条件</p>
        </div>
      </div>
      <span style="margin:18px 0;font-weight: 600;width:200px;display: inline-block;">搜索结果列表</span>
      <el-select v-model="sortValue"
                 placeholder="请选择"
                 style="float:right;line-height:57px">
        <el-option v-for="item in sortOptions"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value">
        </el-option>
      </el-select>
      <div v-loading="tableLoading">
        <search-table v-show="listIf"
                      v-for="(item,key) in tableData"
                      :list="item"
                      :key="'i'+key"></search-table>
        <search-list v-show="!listIf"
                     v-for="(item,key) in tableData"
                     :list="item"
                     :key="'b'+key"
                     :deptIdTemp='deptIdTemp'></search-list>
        <el-pagination @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="page.currentPage"
                       :page-sizes="[10, 20, 30, 40,50,100]"
                       :page-size="page.pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="page.total">
        </el-pagination>
      </div>
    </div>
  </basic-container>
</template>
<script>
  import {PROJECT_DIC} from '@/const/dict'
  import {resultList, getSubjectResultList} from "@/api/planning/result";
  import {getAreaByType} from "@/api/system";
  import {getUserInfo} from "@/api/login";
  import {mapGetters, mapActions} from "vuex";
  import searchList from "@/components/planning/searchList"
  import searchTable from "@/components/planning/searchTable"
  import tYear from '@/components/year/index.vue';

  export default {
    components: {
      searchList,
      searchTable,
      tYear,
    },
    name: "searchTo",
    beforeCreate() {
      getUserInfo().then(response => {
        this.deptIdTemp = response.data.data.sysDept.deptId
      })
    },
    created() {
      window.resultDetail = this.resultDetail;
      this.getAreaDictProvince();
    },

    mounted() {
      this.putAreaByDeptInfo();
    },


    computed: {
      ...mapGetters([
        'permissions',
        "deptInfo"
      ])
    },
    data() {
      const getApplyForCategoryDic = _ => {
        return [{
          label: '全部',
          value: '-1',
        }].concat(PROJECT_DIC.CATEGORY)
      };
      const getPlanningRankDic = _ => {
        return [{
          label: '全部',
          value: '-1',
        }].concat(PROJECT_DIC.PLANNING_RANK)
      };
      const getLevelDic = _ => {
        return [{
          label: '全部',
          value: '-1',
        }].concat(PROJECT_DIC.PLANNING_LEVEL)
      };
      const getYearDic = _ => {
        return [{
          label: '全部',
          value: '-1',
        }].concat(PROJECT_DIC.YEAR)
      };
      const getAchievementDic = _ => {
        return [].concat(PROJECT_DIC.ACHIVEMENTS)
      };
      return {
        activated: false,
        sortValue: '2',
        sortOptions: [
          {
            label: '发布时间正序',
            value: '1'
          },
          {
            label: '发布时间倒序',
            value: '2'
          },
          {
            label: '规划编码正序',
            value: '3'
          },
          {
            label: '规划编码倒序',
            value: '4'
          }
        ],
        headerData: {
          title: '规划成果查询'
        },
        state: '3,4,5',
        planningRankDic: getPlanningRankDic(),
        publicPath: process.env.BASE_URL,
        keyword: '',//关键字
        name: "",
        showAll: true,
        enumArr: [],
        dictObj: {
          label: '全部',
          value: '-1',
        },
        resetSelectedOptions: {
          categorys: "-1",
          planningRanks: "-1",
          planningLevels: "-1",
          area: '-1',
          province: '-1',
          areCode: '-1',
          district: '-1',
          year: '-1'
        },
        selectedOptions: {
          categorys: "-1",
          planningRanks: "-1",
          planningLevels: "-1",
          city: '-1',
          province: '-1',
          county: '-1',
          year: '-1',
          achivements: "0",
          areaCodeLikeRight: '-1'
        },
        option: {
          column: [
            {
              label: "成果库",
              prop: "achivements",
              multiple: false,
              dicData: getAchievementDic(),
            },
            {
              label: "年份",
              prop: "year",
              multiple: false,
              slot: true,
              dicData: getYearDic()
            },
            {
              label: "规划类型",
              prop: "categorys",
              multiple: false,
              dicData: getApplyForCategoryDic()
            },
            {
              label: "发布等级",
              prop: "planningRanks",
              multiple: false,
              dicData: getPlanningRankDic()
            },
            {
              label: "发布层级",
              prop: "planningLevels",
              multiple: false,
              dicData: getLevelDic()
            },
            {
              label: "省级",
              prop: "province",
              multiple: false,
              dicData: [{
                label: '全部',
                value: '-1',
              }],
            },
            {
              label: "市级",
              prop: "city",
              multiple: false,
              dicData: [{
                label: '全部',
                value: '-1',
              }],
            },
            {
              label: "区县",
              prop: "county",
              multiple: false,
              dicData: [{
                label: '全部',
                value: '-1',
              }],
            },
          ]
        },
        page: {
          total: 0, // 总页数
          currentPage: 1,
          pageSize: 10 // 每页显示多少条
        },
        tableData: [],
        tableOption: {
          page: true,
          addBtn: false,
          editBtn: false,
          addRowBtn: false,
          indexLabel: "序号",
          index: true,
          cellBtn: false,
          indexWidth:70,
          delBtn: false,
          columnBtn: false,
          refreshBtn: false,
          filterBtn: false,
          searchBtn: false,
          menuWidth: 100,
          keyId: "id",
          column: [
            {
              label: "规划编码",
              width: 200,
              prop: "pmuc",
              cell: true,
            },
            {
              label: "规划名称",
              width: 300,
              prop: "title",
              cell: true,
              formatter: function (row, value, label, column) {
                return '<a style="cursor: pointer;" onclick="resultDetail(\'' + row.achievementId + '\')">' + value + '</a>';
              },
            },
            {
              label: "年份",
              prop: "year",
              cell: true,
            },
            {
              label: "申报单位",
              prop: "orgName",
              cell: true,
            },
            {
              label: "发布层级",
              prop: "planningLevel",
              type: "select",
              dicData: PROJECT_DIC.APPROVING_AUTHORITY_LEVEL,
              cell: true
            },
            {
              label: "规划类型",
              prop: "category",
              type: "select",
              dicData: PROJECT_DIC.CATEGORY,
              cell: true
            }
          ]
        },
        tableLoading: false,
        areaDictTemp:{},
        deptIdTemp: '',
        searchType: false,
        listIf: false,
        ascs: 'area_code',
        descs: 'release_Date',
        watchControlFlag: false,
      }
    },
    watch: {
      'selectedOptions': {
        deep: true,
        handler(Val) {
          this.page.currentPage = 1
        }
      },
      sortValue: {
        handler(val) {
          this.ascs = '';
          this.descs = '';
          switch (val) {
            case '1':
              this.ascs = 'release_Date,area_code';
              this.getList(this.page);
              return;
            case '2':
              this.ascs = 'area_code';
              this.descs = 'release_Date';
              this.getList(this.page);
              return;
            case '3':
              this.ascs = 'area_code,pmuc';
              this.getList(this.page);
              return;
            case '4':
              this.ascs = 'area_code';
              this.descs = 'pmuc';
              this.getList(this.page);
              return;
          }
        }
      },
      //市级的监听
      'selectedOptions.city'(val) {
        //用watchControlFlag控制监听器有没有作用
        if (this.watchControlFlag) {
          this.selectedOptions.county = '-1';
          //将区县置空
          for (let column of this.option.column) {
            if (column.prop == "county") {
              column.dicData = [{label: '全部', value: '-1'}]
            }
          }
          let cityAreaCode = val.substring(0, 4);
          this.getAreaDictCounty(cityAreaCode);
        } else {

        }

      },
      //省级的监听
      'selectedOptions.province'(val) {
        //用watchControlFlag控制监听器有没有作用
        if (this.watchControlFlag) {
          this.selectedOptions.county = '-1';
          this.selectedOptions.city = '-1';
          //将区县置空
          for (let column of this.option.column) {
            if (column.prop == "county") {
              column.dicData = [{label: '全部', value: '-1'}]
            }
          }
          let provinceAreaCode = val.substring(0, 2);
          this.getAreaDictCity(provinceAreaCode);
        } else {

        }
      },
      'selectedOptions.achivements'(val) {
        if (val == '1') {
          this.searchType = true
        } else {
          this.searchType = false
        }
        this.getList(this.page)
      }
    },
    activated() {
      if (this.activated) {
        this.getList(this.page)
      } else {
        this.activated = true
      }
    },
    methods: {
      ...mapActions([
        'saveListPagePars'
      ]),
      searchTransition(){
        if(this.showAll){
          this.$refs.search.DIC = this.areaDictTemp
        }else {
          this.areaDictTemp = this.$refs.search.DIC;
        }
      },
      getList(page) {
        this.tableLoading = true;
        if (this.searchType) {
          getSubjectResultList(Object.assign({
            current: page.currentPage,
            size: page.pageSize,
            titleLike: this.keyword,
            city: this.selectedOptions.city == '-1' ? '' : this.selectedOptions.city,
            areaCodeLikeRight: this.selectedOptions.areaCodeLikeRight == '-1' ? '' : this.selectedOptions.areaCodeLikeRight,
            year: this.selectedOptions.year == '-1' ? '' : this.selectedOptions.year,
            states: '9',
            ascs: this.ascs,
            descs: this.descs,
          })).then(response => {
            this.listIf = true;
            this.tableData = response.data.data.records;
            this.page.total = response.data.data.total;
            this.tableLoading = false
          })
        } else {
          resultList(Object.assign({
            current: page.currentPage,
            size: page.pageSize,
            titleLike: this.keyword,
            states: this.state,
            ascs: this.ascs,
            descs: this.descs,
          }, this.filterFormData(this.selectedOptions))).then(async response => {
            this.listIf = false;
            this.tableData = await response.data.data.records;
            this.page.total = response.data.data.total;
            this.tableLoading = false
          })
        }

      },
      /**
       * 刷新回调
       */
      refreshChange() {
        this.getList(this.page);
      },
      handleSizeChange(val) {
        this.page.pageSize = val;
        this.getList(this.page)
      },
      handleCurrentChange(val) {
        this.page.currentPage = val;
        this.getList(this.page)
      },
      handleChange(form) {

      },
      setSearchInput(val) {
        this.keyword = val
      },
      // 查询
      searchSubmit(y) {
        //将省级市级县级进行处理
        if (this.selectedOptions.county != -1 && this.selectedOptions.county != '') {
          this.selectedOptions.areaCodeLikeRight = this.selectedOptions.county
        } else if (this.selectedOptions.city != -1 && this.selectedOptions.city != '') {
          this.selectedOptions.areaCodeLikeRight = this.selectedOptions.city.substring(0, 4);
        } else {
          this.selectedOptions.areaCodeLikeRight = this.selectedOptions.province.substring(0, 2);
        }
        this.selectedOptions.areaCodeLikeRight = this.selectedOptions.areaCodeLikeRight.substring(0, 6);
        
        this.selectedOptions.year = y||this.$refs.year.year||'';

        let pars = {
          filter: this.selectedOptions,
          page: this.page.currentPage,
          page_size: this.page.pageSize,
          order: this.sortValue
        };
        let obj = {
          path: this.$route.path,
          pars: pars
        };
        this.saveListPagePars(obj);
        this.page.currentPage = 1
        this.getList(this.page)
      },
      // 重置
      searchReset() {
        this.keyword = '';
        this.selectedOptions = this.resetSelectedOptions;
        this.getList(this.page)
      },
      filterFormData(form) {
        var formMap = {};
        Object.keys(form).forEach(function (name) {
          if (form[name] != -1) {
            formMap[name] = form[name]
          }
        });
        return formMap;
      },
      // 成果详情跳转
      resultDetail(achievementId) {
        let src = `/planning/achievement/detail?id=${achievementId}`;
        this.$router.push({
          path: src
        })
      },
      // 成果编辑
      resultEdit(row, index) {
        let src = `/resultEdit/detail/${row.achievementId}`;
        this.$router.push({
          path: src
        })
      },
      getAreaDictProvince() {
        getAreaByType(Object.assign({
          current: 1,
          size: -1,
          type: "area_code_province"
        })).then(response => {
          let records = response.data.data.records;
          let provinceList = [];
          //加全部
          provinceList.push(this.dictObj);
          for (let item in records) {
            let dictObj = {
              label: records[item].label,
              value: records[item].value
            };
            provinceList.push(dictObj)
          }
          this.$refs.search.DIC['province'] = provinceList;
        })
      },
      getAreaDictCity(provinceCode) {
        getAreaByType(Object.assign({
          current: 1,
          size: -1,
          valueLike: provinceCode,
          type: "area_code_city"
        })).then(response => {
          let records = response.data.data.records;
          let cityList = [];
          cityList.push(this.dictObj);
          for (let item in records) {
            let dictObj = {
              label: records[item].label,
              value: records[item].value
            };
            cityList.push(dictObj)
          }
          this.$refs.search.DIC['city'] = cityList;
        })
      },
      getAreaDictCounty(areaCode) {
        getAreaByType(Object.assign({
          current: 1,
          size: -1,
          valueLike: areaCode,
          type: "area_code_county",
        })).then(response => {
          let records = response.data.data.records;
          let countyList = [];
          countyList.push(this.dictObj);
          for (let item in records) {
            let dictObj = {
              label: records[item].label,
              value: records[item].value
            };
            countyList.push(dictObj)
          }
          this.$refs.search.DIC['county'] = countyList;
        })
      },
      //得到当前部门的信息，搜索当前部门的规划
      async putAreaByDeptInfo() {
        this.selectedOptions.province = this.deptInfo.areaCode.substring(0, 2) + '0000000000';
        await this.getAreaDictCity(this.deptInfo.areaCode.substring(0, 2));

        if (Number(this.deptInfo.areaCode.substring(2, 4)) > 0) {
          this.selectedOptions.city = this.deptInfo.areaCode.substring(0, 4) + '00000000';
          await this.getAreaDictCounty(this.deptInfo.areaCode.substring(0, 4));
        } else {
          this.selectedOptions.city = '-1';
        }

        if (Number(this.deptInfo.areaCode.substring(4, 6)) > 0) {
          this.selectedOptions.county = await this.deptInfo.areaCode.substring(0, 6) + '000000'
        } else {
          this.selectedOptions.county = '-1';
        }

        //放开监听器
        this.watchControlFlag = true;
        this.searchSubmit();

      }

    }
  };
</script>

<style lang="scss" scoped>
  .card-border {
    border: 1px solid #d2d2d2;
    padding: 12px;
  }

  .step-title {
    display: inline-block;
    border-bottom: solid #ec950a;
    padding-bottom: 10px;
    font-weight: 600;
  }

  .step-button {
    float: right;
  }

  .step-img {
    width: 25px;
    position: relative;
    left: 0px;
    top: 7px;
  }

  .form-group {
    margin-top: 1rem;
  }

  .form-label {
    font-weight: 600;
    margin-right: 2rem;
  }

  .form-padding {
    padding-left: 50px;
  }

  .form-label-small {
    font-size: 14px;
    margin-right: 2rem;
  }

  .form-submit {
    float: right;
  }

  .collapse-title {
    margin-top: -1rem;
    text-align: center;
    border-top: 1px solid #dedbdb;
    border-bottom: 1px solid #dedbdb;
  }

  .collapse-title-text {
    color: #4297dc;
    display: inline-block;
    font-size: 15px;
    font-weight: 600;
    margin-left: 0.2rem;
    margin: 10px 0px;
  }

  .collapse-title-img {
    width: 1.2rem;
    position: relative;
    top: 0.25rem;
  }

  .showAll {
    padding: 10px;
    height: 0px;
    overflow: hidden;

    .fade-enter-active {
      transition: opacity 0.9s ease-out;
    }

    .fade-leave-active {
      transition: opacity 0s ease-out;
    }

    .fade-enter,
    .fade-leave-to {
      opacity: 0;
    }

    .fade1-enter-active {
      transition: opacity 0.9s ease-out;
    }

    .fade1-enter,
    .fade1-leave-to {
      opacity: 0;
    }

    clear: both;
    /*margin-top: 6px;*/
  }

  .showAll.active {
    height: auto;
    background: #fff;
    min-height: 150px;
  }

  .imgbtn {
    border-top: 1px solid #ccc;
    margin-top: 6px;
    margin-bottom: 10px;
  }

  .fade-enter-active {
    transition: opacity 0.9s ease-out;
  }

  .fade-leave-active {
    transition: opacity 0s ease-out;
  }

  .fade-enter,
  .fade-leave-to {
    opacity: 0;
  }

  .fade1-enter-active {
    transition: opacity 0.9s ease-out;
  }

  .fade1-enter,
  .fade1-leave-to {
    opacity: 0;
  }

  .search-collapse {
    margin-top: 1rem;
  }

  #searchInput {
    height: 40px;
    border: 1px solid #dadada;
    outline: 0;
    line-height: 40px;
    text-indent: 1rem;
    border-radius: 0.31rem;
  }

  /deep/ .avue-search__title {
    padding: 0 26px;
    margin-left: -13px;
  }

  .el-pagination {
    text-align: right;
    padding: 20px 0;
  }

  .fr {
    float: right;
  }

  .el-dropdown-link {
    cursor: pointer;
    color: #409eff;
  }

  .el-icon-arrow-down {
    font-size: 14px;
  }

  .demonstration {
    display: block;
    color: #8492a6;
    font-size: 14px;
    margin-bottom: 20px;
  }
  /deep/.avue-search__tags--active {
    color: #fff;
    background-color: #1890ff;
    border-radius: 5px;
    padding: 5px 10px;
  }
</style>

